# ui/search_components.py - 搜索组件
import tkinter as tk
from tkinter import ttk
from typing import List, Callable

class SearchManager:
    """搜索管理器"""
    
    def __init__(self, download_manager):
        self.download_manager = download_manager
    
    def search_files(self, keyword: str, file_list=None) -> List:
        """搜索文件（仅搜索名称）"""
        if not keyword:
            return file_list if file_list else self.download_manager.get_file_list()
        
        results = []
        keyword_lower = keyword.lower()
        
        target_list = file_list if file_list else self.download_manager.get_file_list()
        
        for file_info in target_list:
            name = file_info.name.lower() if hasattr(file_info, 'name') else file_info.get("name", "").lower()
            if keyword_lower in name:
                results.append(file_info)
        
        return results
    
    def search_versions(self, package_name: str, keyword: str) -> List:
        """搜索特定包的版本"""
        package_info = self.download_manager.get_package_info(package_name)
        if not package_info:
            return []
        
        results = []
        keyword_lower = keyword.lower()
        
        for version, version_info in package_info.versions.items():
            if keyword_lower in version:
                results.append((version, version_info))
        
        return results

class SearchBar:
    """搜索栏组件"""
    
    def __init__(self, parent, search_callback: Callable, placeholder: str = "搜索..."):
        self.parent = parent
        self.search_callback = search_callback
        
        # 创建搜索框架
        self.frame = ttk.Frame(parent)
        
        # 搜索标签
        ttk.Label(self.frame, text="搜索:").pack(side=tk.LEFT, padx=(0, 5))
        
        # 搜索输入框
        self.search_var = tk.StringVar()
        self.search_entry = ttk.Entry(
            self.frame, 
            textvariable=self.search_var,
            width=30
        )
        self.search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 设置占位符文本
        self.placeholder = placeholder
        self.search_entry.insert(0, self.placeholder)
        self.search_entry.config(foreground='grey')
        
        # 绑定事件
        self.search_entry.bind('<FocusIn>', self._on_entry_focus_in)
        self.search_entry.bind('<FocusOut>', self._on_entry_focus_out)
        self.search_var.trace('w', self._on_search_change)
        self.search_entry.bind('<Return>', self._on_search_enter)
        
        # 搜索按钮
        self.search_button = ttk.Button(
            self.frame, 
            text="搜索", 
            command=self._perform_search
        )
        self.search_button.pack(side=tk.LEFT, padx=(5, 0))
        
        # 清空按钮
        self.clear_button = ttk.Button(
            self.frame,
            text="清空",
            command=self._clear_search
        )
        self.clear_button.pack(side=tk.LEFT, padx=(5, 0))
    
    def _on_entry_focus_in(self, event):
        """输入框获得焦点事件"""
        if self.search_entry.get() == self.placeholder:
            self.search_entry.delete(0, tk.END)
            self.search_entry.config(foreground='black')
    
    def _on_entry_focus_out(self, event):
        """输入框失去焦点事件"""
        if not self.search_entry.get():
            self.search_entry.insert(0, self.placeholder)
            self.search_entry.config(foreground='grey')
    
    def _on_search_change(self, *args):
        """搜索内容改变事件"""
        current_text = self.search_var.get()
        if current_text and current_text != self.placeholder:
            self.search_callback(current_text)
    
    def _on_search_enter(self, event):
        """回车键搜索事件"""
        self._perform_search()
    
    def _perform_search(self):
        """执行搜索"""
        search_text = self.search_var.get()
        if search_text and search_text != self.placeholder:
            self.search_callback(search_text)
    
    def _clear_search(self):
        """清空搜索"""
        self.search_var.set("")
        self.search_entry.delete(0, tk.END)
        self.search_entry.insert(0, self.placeholder)
        self.search_entry.config(foreground='grey')
        self.search_callback("")
    
    def get_frame(self):
        """获取搜索栏框架"""
        return self.frame
    
    def get_search_text(self):
        """获取搜索文本"""
        text = self.search_var.get()
        return text if text != self.placeholder else ""
    
    def set_search_text(self, text: str):
        """设置搜索文本"""
        self.search_var.set(text)
        if text:
            self.search_entry.config(foreground='black')
        else:
            self._clear_search()